﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple_PM.Models;
using Simple_PM.Services.Dashboard;
using Simple_PM.Services.Task;

namespace Simple_PM.Controllers
{
    [Authorize]
    public class TaskController : Controller
    {
        private readonly ITaskService _taskService;
        public TaskController(ITaskService taskService)
        {
            _taskService = taskService;
        }

        public ActionResult CreateTask()
        {
            return View();
        }

        public ActionResult AddTask()
        {
            var model = new TaskModel();
            model.CategoryList = _taskService.GetCategoriesList();

            return View(model);
        }

        [HttpPost]
        public ActionResult AddTask(TaskModel model)
        {
            _taskService.AddTask(model, User.Identity.Name);
            return RedirectToAction("Index", "Dashboard");
        }

        public JsonResult LoadCategories()
        {
            var model = _taskService.GetCategoriesCount(User.Identity.Name);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public JsonResult LoadTasks(string filterStatus, string category)
        {
            var model = _taskService.LoadTasks(filterStatus, category, User.Identity.Name);

            if (filterStatus == "Completed")
            {
                return Json(model , JsonRequestBehavior.AllowGet);
            }
            
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditTask(string strTaskId)
        {
            int taskId = int.Parse(strTaskId);
            var model = _taskService.GetSingleTask(taskId);

            return View(model);
        }

        [HttpPost]
        public ActionResult EditTask(TaskModel model)
        {
            _taskService.UpdateSingleTask(model);
            return RedirectToAction("Index", "Dashboard");
        }

        public JsonResult TaskCompleted(string strTaskId)
        {
            int taskId = int.Parse(strTaskId);
            bool isClosed = _taskService.CloseTask(taskId);

            return Json(isClosed, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ReopenTask(string strTaskId)
        {
            int taskId = int.Parse(strTaskId);
            bool isReopened = _taskService.ReopenTask(taskId);

            return Json(isReopened, JsonRequestBehavior.AllowGet);
        }

        public ActionResult DeleteTask(string strTaskId)
        {
            int taskId = int.Parse(strTaskId);
            bool isDeleted = _taskService.DeleteTask(taskId);

            return Json(isDeleted, JsonRequestBehavior.AllowGet);
        }
    }
}
